const {deleteData, update, add, page, list, detail, save, session, mlist, info, lists, query, aireportCheck, aireportGenerate, aireportContent} = require("../../api/index.js")
const utils = require("../../utils/index.js")
let reportCheckTimer = null;
Page({
    data: {
        title: '',
        user: {},
                pageIsAuth: false,
        token: '',
        baseURL: '',
        id: getApp().globalData.detailId,
        userId: getApp().globalData.userInfo.id,
        detailList: {},
        payAuth: "",
        picture: "",
                goodname: "",
                        shhf: '',
            sfshIndex: 0,
            sfshOptions: ['通过', '不通过', '待审核'],
            isAuth: '',
            isAuthFront: '',
           xiangmushenqingisAuthFront: '',
           isAuthxiangmushenqing: '',
            sixinAuthFront: false,
            sixinisAuth: false,
            chatList: [],
            chatForm: {
                content: ''
            },
            chatTimer: null,
            fpic: '',
            fname: '',
            fid: "",
            mpic: '',
        showFullIntro: false,
        // AI报告相关状态
        isGeneratingReport: false,
        reportDialogVisible: false,
        reportContent: '',
        reportError: '',
        reportCheckInterval: null,
    },
    async onLoad(option) {
        let authobj = {}
                authobj['pageIsAuth'] = wx.getStorageSync('isAuth')
       authobj['isAuthxiangmushenqing'] = utils.isAuth('xiangmuxinxi', '申请')
              authobj['xiangmushenqingisAuthFront'] = utils.isAuthFront('xiangmuxinxi', '申请')
                this.setData(authobj)
        let myid = option?.id ? option?.id : getApp().globalData.detailId;
        const user = wx.getStorageSync("userSession");
        this.setData({
            user,
            id: myid,
                isAuth: utils.isAuth('xiangmuxinxi', '审核'),
                isAuthFront: utils.isAuthFront('xiangmuxinxi', '审核'),
            token: wx.getStorageSync('token'),
            baseURL: wx.getStorageSync('baseURL') + '/'
        })
        await this.handleUpdateData()
    },
        async noFriendInit() {
            let detailList = this.data.detailList;
            let Obj = {}
                Obj['sixinAuthFront'] = utils.isAuthFront('xiangmuxinxi', '私信')
                Obj['sixinisAuth'] = utils.isAuth('xiangmuxinxi', '私信')
                if (detailList.touxiang) {
                    Obj['fpic'] = detailList.touxiang.split(',')[0]
                } else if (detailList.headportrait) {
                    Obj['fpic'] = detailList.headportrait.split(',')[0]
                }
                Obj['mpic'] = wx.getStorageSync('avatarurl');
            this.setData(Obj)
        },
//立即预订
    orderTap() {
        if (this.data.activeSeat.length <= 0) {
            wx.showToast({
                title: '请选择需要预订的位置',
                icon: 'none'
            })
            return
        }
        const userInfo = getApp().globalData.userInfo
        const activeSeat = this.data.activeSeat.join(',') + ',' + this.data.detailList.selected
        let data = {
            orderid: this.createOrderId(),
            tablename: 'xiangmuxinxi',
            userid: userInfo.id,
            goodid: this.data.detailList.id,
            goodname: this.data.detailList.xiangmumingcheng,
            buynumber: this.data.activeSeat.length,
            total: 0,
            discounttotal: 0,
            address: this.data.activeSeat,
            status: '已支付',
            discountprice: this.data.detailList.vipprice,
             picture: this.data.picture[0],
        }
        if (this.data.detailList?.price) {
            data['status'] = '未支付'
            data['price'] = this.data.detailList.price;
            data['total'] =wx.getStorageSync('vip') == '是'? 0 :
            parseFloat(this.data.detailList.price * this.data.activeSeat.length).toFixed(2)
            getApp().globalData.total = data.total;
            wx.showModal({
                title: '提示',
                content: '是否预订选中座位',
                complete: async (res) => {
                    if (res.confirm) {
                        wx.setStorageSync('orderGoods', [data])
                                                wx.navigateTo({
                            url: "/pages/shop-order/orders-confirm?type=1&seat=1"
                        })
                    }
                }
            })
        }

    }
    ,
    chapterClick(e) {
        const item = e.currentTarget.dataset.item;
        const user = this.data.user;

        if (!this.data.userId) {
            wx.showToast({
                title: '请先登录',
                icon: "none"
            })
            setTimeout(() => {
                wx.navigateTo({
                    url: `/pages/login/login`,
                })
            }, 1500)
            return
        }
        let that = this.data;
    },
    authTap() {
        if (!this.data.token) {
            wx.showToast({
                title: '请先登陆',
                icon: 'none'
            })
            return
        }
    },
    // 去除Markdown符号，仅保留纯文本
    stripMarkdown(md) {
        if (!md) return '';
        // 去除 #、*、-、_、>、` 等符号
        return md.replace(/[\#\*\-\_\>\`]/g, '').replace(/\n+/g, ' ').trim();
    },
    async handleUpdateData() {
        let nowTable = wx.getStorageSync("nowTable");
        if (nowTable) {
            const res = await session(nowTable)
            if (res.code == 0) {
                getApp().globalData.userInfo = res?.data;
                let userId = res?.data.id;
                this.setData({
                    userId
                })
            }
        }

// 更新当前页面的数据
        var that = this;
        getApp().globalData.detailId == null ? getApp().globalData.detailId = wx.getStorageSync('detailId') : "";
        const id = getApp().globalData.detailId;
        if (id) {
            const {data} = await detail("xiangmuxinxi", id)
            this.setData({
                payAuthFront: utils.isAuthFront('xiangmuxinxi', '支付'),
                payAuth: utils.isAuth('xiangmuxinxi', '支付')
            })
                    data.shhf == null ? data.shhf = "" : ''
            let objClo = {}
objClo['picture'] = data.xiangmutupian ?.split(',').map(item=>{
return  item.indexOf('http') !== -1?item: item = this.data.baseURL+item?.split(",")[0].replace('upload','flie');
});
    if(data.xiangmuxiangqing){
        data.xiangmuxiangqing = utils.addImgWidthStyle(data.xiangmuxiangqing, '100%')
    }
                objClo['shhf'] = data.shhf;
            objClo['detailList'] = data;
            // 新增简介截取字段
            objClo['introShort'] = data.xiangmujianjie
                ? (data.xiangmujianjie.length > 50 ? data.xiangmujianjie.slice(0, 50) : data.xiangmujianjie)
                : '';
            // 新增简介纯文本字段
            objClo['introShortPlain'] = data.xiangmujianjie
                ? (this.stripMarkdown(data.xiangmujianjie).slice(0, 50))
                : '';
            this.setData(objClo)
                this.noFriendInit()
            if (!this.data.token) {
                return
            }
        }
        this.setData({
title: this.data.detailList.xiangmumingcheng,
        });
    },

    onUnload: function () {
        getApp().globalData.detailList = {}
    },
    async listUpdate(name) {
        const predetailList = this.data.predetailList
        const detailList = this.data.detailList
        predetailList.shangpintupian = this.data.picture[0]
        if (name == "thumbsupNumber") {
// 点赞
            predetailList.thumbsupNumber = predetailList.thumbsupNumber + 1
            detailList.thumbsupNumber = detailList.thumbsupNumber + 1
        }
        if (name == "cancelthumb") {
// 取消点赞
            predetailList.thumbsupNumber = predetailList.thumbsupNumber - 1
            detailList.thumbsupNumber = detailList.thumbsupNumber - 1
        }
        if (name == "crazilyNumber") {
            predetailList.crazilyNumber = predetailList.crazilyNumber + 1
            detailList.crazilyNumber = detailList.crazilyNumber + 1
        }
        if (name == "cancelCrazily") {
            predetailList.crazilyNumber = predetailList?.crazilyNumber - 1
            detailList.crazilyNumber = detailList.crazilyNumber - 1
        }
        if (name == 'cancelislike') {
            predetailList.storeupNumber = predetailList.storeupNumber - 1
            detailList.storeupNumber = detailList.storeupNumber - 1

        }
        if (name == "islike") {
            predetailList.storeupNumber = predetailList.storeupNumber + 1
            detailList.storeupNumber = detailList.storeupNumber + 1
        }
        this.setData({
            detailList
        })
        const resUpdate = await update('xiangmuxinxi', predetailList)
        if (resUpdate.code == 0) {
            this.setData({
                predetailList,
                "detailList.crazilyNumber": predetailList.crazilyNumber
            })

        }


    },
        cancelShow() {
            this.selectComponent('#chatFrame').hideFrame();
            clearTimeout(this.data.chatTimer)

        },
            async chatClick() {
                if (!this.data.token) {
                    wx.showToast({
                        title: '请登录后再操作',
                        icon: "none"
                    })
                    setTimeout(() => {
                        wx.navigateTo({
                            url: "/pages/login/login"
                        })
                    }, 1500)

                    return
                }
                let user = getApp().globalData.userInfo ? getApp().globalData.userInfo : {};
                            if (this.data.detailList.fuzerenzhanghao == user.fuzerenzhanghao) {
                                wx.showToast({
                                    title: '不能给自己发信息',
                                    icon: "none"
                                })
                                return
                            }
                let Obj = {}
                let res = await query('chuangyezhe', {
                    xuehao: this.data.detailList.fuzerenzhanghao
                })
                if (!res.data) {
                    wx.showToast({
                        title: '未找到负责人信息',
                        icon: "none"
                    })
                    return
                }
                Obj['fid'] = res.data.id;
                Obj['fname'] = res.data.xuehao;
                if (res.data.touxiang) {
                    Obj['fpic'] = res.data.touxiang.split(',')[0]
                } else if (res.data.headportrait) {
                    Obj['fpic'] = res.data.headportrait.split(',')[0]
                }
                this.setData(Obj)

                this.getChatList()
                this.selectComponent('#chatFrame').showFrame();
            },
        async saveGood() {
            clearTimeout(this.data.chatTimer)
            this.cancelShow()
            let _this = this.data;
            let res = await page('chatfriend', {
                fid: _this.fid,
                uid: _this.userId
            })
            if (!res.data.list.length) {
                await add('chatfriend', {
                    fid: _this.fid,
                    uid: _this.userId,
                    name: _this.fname,
                    picture: _this.fpic,
                    type: 2,
                    tablename: 'fuzeren'
                })
                await add('chatfriend', {
                    fid: _this.fid,
                    uid: _this.userId,
                    name: wx.getStorageSync("nickname"),
                    picture: _this.mpic,
                    type: 2,
                    tablename: wx.getStorageSync("nowTable")
                })
            }
            await add('chatmessage', {
                fid: _this.fid,
                uid: _this.userId,
                content: _this.picture[0],
                format: 2
            })

            this.setData({
                chatForm: {
                    content: ''
                }
            })
            this.getChatList()
        },
        async getChatList() {
            let res = await mlist('chatmessage', {
                page: 1,
                limit: 1000,
                fid: this.data.fid,
                uid: this.data.userId,
            })

            setTimeout(() => {
                this.setData({
                    currentIndex: 'i' + (this.data.chatList.length - 1)
                })

            }, 0)
            this.setData({
                chatList: res?.data?.list.map((v) => {
                    if (v.format === 2) {
                        v.content = v.content.replace('upload', 'file')
                    }
                    return v
                }),
                chatTimer: setTimeout(() => {
                    this.getChatList()
                }, 5000)
            })
        },
        clearChat(e) {
            if (!e.show) {
                clearTimeout(this.data.chatTimer)
            }
        },
        preViewImg(e) {
            const img = e.currentTarget.dataset.value;
            wx.previewImage({
                urls: [img],
                current: img
            })
        },
        async uploadSuccess() {
            let userInfo = getApp().globalData.userInfo
            clearTimeout(this.data.chatTimer)
            wx.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: async (res) => {
                    let _this = this.data;
// 上传网络图片
                    wx.uploadFile({
                        url: `${_this.baseURL}file/upload`,
                        filePath: res.tempFilePaths[0],
                        name: 'file',
                        header: {
                            'Token': wx.getStorageSync('token')
                        },
                        success: async (uploadFileRes) => {
                            let _this = this.data;
                            let result = JSON.parse(uploadFileRes.data);
// result.file是上传成功为网络图片的名称
                            let res = await page('chatfriend', {
                                uid: userInfo.id,
                                fid: _this.fid,
                            })
                            if (!res.data.list.length) {
                                await page('chatfriend', {
                                    uid: _this.fid,
                                    fid: userInfo.id,
                                    name: _this.fname,
                                    picture: _this.fpic,
                                    type: 2,
                                    tablename: 'yonghu'
                                })
                                await page('chatfriend', {
                                    fid: userInfo.id,
                                    uid: _this.fid,
                                    name: wx.getStorageSync("nickname"),
                                    picture: _this.mpic,
                                    type: 2,
                                    tablename: wx.getStorageSync("nowTable")
                                })

                            }
                            await add('chatmessage', {
                                uid: userInfo.id,
                                fid: _this.fid,
                                content: 'file/' + result.file,
                                format: 2
                            })
                            _this.chatForm = {
                                content: ''
                            }
                            this.getChatList()
                        }
                    })


                }
            })


        },
        async addChat() {
            let userInfo = getApp().globalData.userInfo
            clearTimeout(this.data.chatTimer)
            if (!this.data.chatForm.content) {
                return
            }
            let _this = this.data;
            let res = await page('chatfriend', {
                uid: userInfo.id,
                fid: this.data.id,
            })
            if (!res?.data?.list?.length) {
                await add('chatfriend', {
                    uid: userInfo.id,
                    fid: _this.fid,
                    name: this.data.fname,
                    picture: this.data.fpic,
                    type: 2,
                    tablename:  'fuzeren' ,
                })
                await add('chatfriend', {
                    fid: userInfo.id,
                    uid: _this.fid,
                    name: wx.getStorageSync("nickname"),
                    picture: this.data.mpic,
                    type: 2,
                    tablename: wx.getStorageSync("nowTable")
                })
            }

            await add('chatmessage', {
                fid: _this.fid,
                uid: userInfo.id,
                content: this.data.chatForm.content,
                format: 1
            })

            this.setData({
                chatForm: {
                    content: ''
                }
            })
            this.getChatList()
        },


        contentTap(e) {
            let chatForm = Object.assign(this.data.chatForm, {})
            chatForm['content'] = e.detail.value;
            this.setData(chatForm)
        },
    previewImgTap(e) {
        var currentUrl = e.currentTarget.dataset.currenturl
        const list = this.data.picture.map(v => {
            return this.data.baseURL + v
        })
        wx.previewImage({
            urls: list, // 需要预览的图片链接列表
            current: currentUrl // 设置当前预览的图片
        });
                                                                                                                                    },


        onPayTap() {
        if (!wx.getStorageSync('token')) {
            wx.showToast({
                title: '请先登录',
                icon: "none"
            })
            setTimeout(() => {
                wx.navigateTo({
                    url: `/pages/login/login`
                })
            }, 1000)
            return
        }
            if (this.data.detailList.sfsh != '是') {
                wx.showToast({
                    title: '请审核通过后再操作',
                    icon: "none"
                })
                return
            }
        const baseURL = wx.getStorageSync('baseURL')
        let data = this.data.detailList
                                data["xiangmutupian"] = data.xiangmutupian
        data['buynumber'] = 1
        wx.setStorageSync('payObject', data);
        wx.setStorageSync('paytable', 'xiangmuxinxi');
        
                                wx.navigateTo({
            url: "/pages/pay-confirm/pay-confirm?type=1"
        })
    },
        onSHTap() {
            this.selectComponent('#bottomFrame').showFrame();
        },
        canlreply() {
            this.selectComponent('#bottomFrame').hideFrame();
        },
    async reply() {
        const detailList = this.data.detailList
                        detailList['shhf'] = this.data.shhf
                                                                                                                                                                const res = await update("xiangmuxinxi", detailList)
        if (res.code == 0) {
            setTimeout(function () {
                wx.showToast({
                    title: '回复成功',
                    icon: "none"
                })
            }, 1000)

            this.handleUpdateData()
        }
        this.selectComponent('#bottomFrame').hideFrame();
    },
async onShow() {
    },
                                        sfshChange(e) {
            var sfsh = '';
            this.data.sfshOptions[e.detail.value] == '通过' ? sfsh = '是' : (this.data.sfshOptions[e.detail.value] == '不通过' ? sfsh = '否' : this.data.sfshOptions[e.detail.value] == '待审核' ? sfsh = '待审核' : '')
            this.setData({
                sfshIndex: e.detail.value,
                'detailList.sfsh': sfsh
            })
        },
        onSHTap() {
            this.selectComponent('#bottomFrame').showFrame();
        },
//免费试读

// 下载
    download(e) {
        let url = e.currentTarget.dataset.url
        url = wx.getStorageSync('baseURL') + '/' + url;
        wx.downloadFile({
            url: url,
            success: (res) => {
                if (res.statusCode === 200) {
                    wx.showToast({
                        title: '下载成功',
                        icon: "none"
                    })

                    const filePath = res.tempFilePath
                    wx.openDocument({
                        filePath: filePath,
                        showMenu: true,
                        success: function (res) {
                            console.log('打开文档成功')
                        }
                    })
                    console.log('点击查看文件', filePath);
                                                                            }
            }
        });
    },
// 跨表
            async onAcrossTap(e) {

// (tableName,crossOptAudit,statusColumnName,tips,statusColumnValue)
        const info = e.currentTarget.dataset.info;
        const crossOptAudit = info.split(",")[1].replace(/'/g, '')

        const token = wx.getStorageSync("token")
        if (!this.data.token) {
                        wx.showToast({
                title: '请登录后再操作',
                icon: "none"
            })
            return
        }

            if (crossOptAudit == '是' && this.data.detailList?.sfsh != '是') {
                                wx.showToast({
                    title: '请审核通过后再操作',
                    icon: "none"
                })
                return
            }
        let pagetableName = info.split(",")[0]
        const statusColumnName = info.split(",")[2]
        const tips = info.split(",")[3]
        let statusColumnValue = info.split(",")[3]
        let type = info.split(",")[6];
        type ? type * 1 : type = 1;
        statusColumnValue = statusColumnValue.replace(/^'|'$/g, '');
        wx.setStorageSync('crossTable', 'xiangmuxinxi');
        wx.setStorageSync(`crossObj`, this.data.detailList);
        wx.setStorageSync('statusColumnName', statusColumnName?.substring(1, statusColumnName?.length - 1))
        wx.setStorageSync('tips', tips.substring(1, tips?.length - 1))
        let keyname = statusColumnValue?.split('[')[0]
        let statusColumnValueindex = statusColumnValue?.split('[')[1]?.replace(']', '')
        keyname = keyname ? keyname.replace('CrossSelect', '') : ''

        wx.setStorageSync('statusColumnValue', statusColumnValue)
        if (statusColumnName != '' && !statusColumnName.startsWith("[")) {
            var obj = this.data.detailList

            for (var o in obj) {
                if (statusColumnName.includes(o) && statusColumnValue == obj[o]) {
                    wx.showToast({
                        title: tips,
                        icon: "none"
                    })
                    return
                }
            }
        }
        getApp().globalData.detailId = this.data.detailList.id
        getApp().globalData.detailList = this.data.detailList
        wx.navigateTo({
            url: `/pages/${pagetableName}/update-and-add?cross=true`,
        })

    },
    onViewProfile() {
        let fuzerenzhanghao = this.data.detailList.fuzerenzhanghao;
        if (!fuzerenzhanghao) {
            wx.showToast({
                title: '无负责人账号',
                icon: 'none'
            });
            return;
        }
        fuzerenzhanghao = fuzerenzhanghao.trim();
        // 用负责人账号作为学号查chuangyezhe表
        query('chuangyezhe', { xuehao: fuzerenzhanghao }).then(res => {
            let data = res.data;
            let xuehao = null;
            if (res.code === 0) {
                if (Array.isArray(data) && data.length > 0 && data[0].xuehao) {
                    xuehao = data[0].xuehao;
                } else if (data && data.xuehao) {
                    xuehao = data.xuehao;
                }
            }
            if (xuehao) {
                wx.navigateTo({
                    url: `/pages/aipersonal/list?xuehao=${xuehao}`
                });
            } else {
                wx.showToast({
                    title: '未找到负责人电子档案',
                    icon: 'none'
                });
            }
        });
    },
    async onAiReportTap() {
        const detailList = this.data.detailList;
        if (!detailList || !detailList.xiangmumingcheng) {
            wx.showToast({
                title: '项目信息不完整，无法生成报告',
                icon: 'none'
            });
            return;
        }
        const xiangmumingcheng = detailList.xiangmumingcheng;
        const reportUrl = this.data.baseURL + 'aireport/content?xiangmumingcheng=' + encodeURIComponent(xiangmumingcheng);
        try {
            const res = await aireportCheck(xiangmumingcheng);
            if (res && res.code === 0) {
                const status = res.status;
                if (status === 'completed') {
                    wx.navigateTo({
                        url: '/pages/aireport/detail?url=' + encodeURIComponent(reportUrl)
                    });
                } else if (status === 'generating') {
                    wx.showToast({ title: 'AI报告正在生成中，请稍后再试', icon: 'none' });
                } else {
                    await aireportGenerate(xiangmumingcheng);
                    wx.showToast({ title: '已开始生成AI报告，稍后可点击查看', icon: 'none' });
                }
            } else {
                await aireportGenerate(xiangmumingcheng);
                wx.showToast({ title: '已开始生成AI报告，稍后可点击查看', icon: 'none' });
            }
        } catch (e) {
            wx.showToast({ title: 'AI报告请求失败，请稍后再试', icon: 'none' });
        }
    },
    // Markdown转HTML的简单实现
    md2html(md) {
        if (!md) return '';
        let html = md;
        // 标题
        html = html.replace(/^###### (.*)$/gm, '<h6>$1</h6>');
        html = html.replace(/^##### (.*)$/gm, '<h5>$1</h5>');
        html = html.replace(/^#### (.*)$/gm, '<h4>$1</h4>');
        html = html.replace(/^### (.*)$/gm, '<h3>$1</h3>');
        html = html.replace(/^## (.*)$/gm, '<h2>$1</h2>');
        html = html.replace(/^# (.*)$/gm, '<h1>$1</h1>');
        // 无序列表
        html = html.replace(/^\s*[-*] (.*)$/gm, '<li>$1</li>');
        html = html.replace(/(<li>.*<\/li>)/gms, '<ul>$1</ul>');
        // 粗体 **text** 或 __text__
        html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
        html = html.replace(/__(.*?)__/g, '<strong>$1</strong>');
        // 斜体 *text* 或 _text_
        html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
        html = html.replace(/_(.*?)_/g, '<em>$1</em>');
        // 换行
        html = html.replace(/\n/g, '<br/>');
        return html;
    },

    onShowFullIntro() {
        const md = this.data.detailList.xiangmujianjie || '';
        const html = this.md2html(md);
        this.setData({ showFullIntro: true, introHtml: html });
    },

    onHideFullIntro() {
        this.setData({ showFullIntro: false });
    },
    stopPopup() {
        // 阻止冒泡，防止点击弹窗内容关闭弹窗
    },
    /**
     * 加好友（和添加导师好友逻辑一致，添加项目负责人为好友）
     */
    async addFriendClick() {
        const userInfo = wx.getStorageSync('userSession') || getApp().globalData.userInfo;
        const detailList = this.data.detailList;
        if (!userInfo || !userInfo.id) {
            wx.showToast({ title: '请登录后再操作', icon: 'none' });
            setTimeout(() => { wx.navigateTo({ url: '/pages/login/login' }); }, 1500);
            return;
        }
        if (!detailList.fuzerenzhanghao) {
            wx.showToast({ title: '无负责人账号', icon: 'none' });
            return;
        }
        // 通过负责人账号查负责人用户id
        const resFzr = await query('chuangyezhe', { xuehao: detailList.fuzerenzhanghao });
        let fzrUser = null;
        if (resFzr.code === 0) {
            if (Array.isArray(resFzr.data) && resFzr.data.length > 0) {
                fzrUser = resFzr.data[0];
            } else if (resFzr.data && resFzr.data.id) {
                fzrUser = resFzr.data;
            }
        }
        if (!fzrUser || !fzrUser.id) {
            wx.showToast({ title: '未找到负责人信息', icon: 'none' });
            return;
        }
        if (fzrUser.id == userInfo.id) {
            wx.showToast({ title: '不能申请自己为好友', icon: 'none' });
            return;
        }
        // 先查对方是否已申请/已是好友
        let res = await page('chatfriend', { fid: userInfo.id, uid: fzrUser.id });
        if (res.data.list.length) {
            if (res.data.list[0].type == 1) {
                wx.showToast({ title: '两人已经是好友了', icon: 'none' });
                return;
            } else if (res.data.list[0].type == 0) {
                wx.showToast({ title: '已经发送了好友申请，请等待对方通过！', icon: 'none' });
                return;
            }
        }
        res = await page('chatfriend', { fid: fzrUser.id, uid: userInfo.id, type: 0 });
        if (res.data.list.length) {
            wx.showToast({ title: '对方已发送好友申请，请前往个人中心通过', icon: 'none' });
            return;
        }
        await add('chatfriend', {
            uid: fzrUser.id,
            fid: userInfo.id,
            type: 0,
            name: wx.getStorageSync('nickname'),
            picture: wx.getStorageSync('avatarurl'),
            tablename: wx.getStorageSync('nowTable')
        });
        wx.showToast({ title: '好友申请发送成功', icon: 'none' });
    },
})